/*
 * Copyright 2009-2010 the original author or authors.
 *
 * Licensed under the Apache license, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.internna.iwebjtracker.javamail.model;

import javax.mail.MessagingException;
import javax.mail.Transport;
import org.internna.iwebjtracker.server.connection.ServerConnection;
import org.internna.iwebmvc.IWebMvcException;

/**
 * A wrapper to the mail session.
 *
 * @author Jose Noheda
 * @since 1.0
 */
public final class JavamailSessionWrapper implements ServerConnection {

    private boolean open = true;
    private Transport transport;

    /**
     * Establish the new physical connection.
     *
     * @param transport any
     */
    public void setTransport(Transport transport) {
        this.transport = transport;
    }

    /**
     * Obtains the connection.
     *
     * @return
     */
    public Transport getTransport() {
        return transport;
    }

    /**
     * Determines if this connection can send messages.
     *
     * @return true if a transport is configured.
     */
    @Override public boolean isOpen() {
        return open && transport != null && transport.isConnected();
    }

    /**
     * Delegates to isOpen().
     *
     * @return true if the connection is open
     */
    @Override public boolean isClosable() {
        return isOpen();
    }

    @Override public boolean keepAlive() {
        return true;
    }

    @Override public int keepAliveTimeout() {
        return 0;
    }

    /**
     * Closes the transport.
     */
    @Override public void close() {
        if (open && (transport != null)) {
            try {
                transport.close();
            } catch (MessagingException ex) {
                throw new IWebMvcException(ex);
            } finally {
                open = false;
                transport = null;
            }
        }
    }

}
